/*
 * ZooServlet.java
 *
 * Created on March 20, 2004, 10:43 AM
 */

import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import java.io.*;
import org.w3c.dom.*;


public class WarServlet extends HttpServlet {

    public final static String
        /** The name of the stylesheet. */
        XSLT_NAME = "war",
        /** The name of the XML doc. */
        XML_NAME = "warXml";

    /** Initializes the servlet.
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        ServletContext webApp = this.getServletContext();

        try {
            // Get concrete implementation
            TransformerFactory tFactory = TransformerFactory.newInstance();
            // Create a reusable templates for a particular stylesheet
            String filePath = webApp.getRealPath( this.getInitParameter( XSLT_NAME ) );
            Templates templates = tFactory.newTemplates( new StreamSource( filePath ) );
            // Register the transformer to the Web app
            webApp.setAttribute( XSLT_NAME, templates );

            // Get concrete implementation
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            // Need a parser that support namespaces
            dFactory.setNamespaceAware( true );
            // Create the parser
            DocumentBuilder parser = dFactory.newDocumentBuilder();
            // Parse the XML document
            filePath = webApp.getRealPath( this.getInitParameter( XML_NAME ) );
            Document doc = parser.parse( filePath );
            // Register the XML doc to the Web app
            webApp.setAttribute( XML_NAME, new DOMSource( doc ) );
        } catch (Exception ex) {
            throw new ServletException( ex );
        }
    }

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException {
        ServletContext webApp = this.getServletContext();

        try {
            // Get the registered transformer
            Templates templates = (Templates) webApp.getAttribute( XSLT_NAME );
            // Create a transformer
            Transformer transformer = templates.newTransformer();

            // Create the stream that will receive the result of the transformation
            ByteArrayOutputStream htmlStreamResult = new ByteArrayOutputStream();

            // Get the registered XML source
            Source xmlSource = (Source) webApp.getAttribute( XML_NAME );

            // Get the parameter to sort the list of animals
            String sort = request.getParameter( "liste-par-nom" );
            if ( sort != null ) {
                transformer.setParameter( "liste-par-nom", Boolean.TRUE );
            }
            // Transform input XML doc in HTML stream
            transformer.transform( xmlSource, new StreamResult( htmlStreamResult ) );

            // Send the HTML stream to the client
            response.setContentType("text/html");
            ServletOutputStream servletOutputStream = response.getOutputStream();
            byte[] byteContent = htmlStreamResult.toByteArray();
            response.setContentLength( byteContent.length );
            servletOutputStream.write( byteContent );
        } catch (Exception ex) {
            throw new ServletException( ex );
        }
    }

    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Zoo";
    }
    
}
